import React from "react";
import PropTypes from "prop-types";
import { Popup, Toast } from "antd-mobile";
import { Selector } from "pages/components/selector";
import { S_SYS_NAME } from "pages/signTask/sign-config";
import axios from "src/api/index";
import Btns from "pages/components/btns";
import WorkflowStep from "./workflow-step";

class WorkflowCommit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            options: [],
            selectValue: undefined,
            defCheckAll: false, //是否默认选中所有的人员，false不选，true全选
            isOneSelect: false, // 会否自选流程
            noPass: false, //某个流程没人审核人
            nodeList: [], // 审核节点
        };
    }

    componentDidUpdate(preProps, preState) {
        if (!preState.show && this.state.show) {
            const { baseUrl } = this.props;
            const affix = S_SYS_NAME === "gsm" ? "_" : "/";
            this.setState({
                checkUrl: baseUrl + affix + "chk", //审核
                discommitUrl: baseUrl + affix + "discommit", //撤回
                rollBackUrl: baseUrl + affix + "rollBack", //退回
                commitUrl: baseUrl + affix + "start", //提交审核
            });
            this.getOpts();
        }
    }

    getOpts = async () => {
        const { workflowModule, userData } = this.props;
        let formTypeVal = workflowModule;
        if (S_SYS_NAME === "gsm") {
            //监理工作
            formTypeVal = workflowModule + "-" + userData.projId;
        }
        const res = await axios({
            method: "get",
            url: "/workflow/findProcessDefinition",
            params: {
                formType: formTypeVal,
            },
        });
        if (res.success) {
            if (!res.data.length) {
                Toast.show({
                    content: "获取工作流节点信息失败！请确认是否已配置对应工作流。",
                });
                this.visibleCb();
                return;
            }
            let options = [];
            res.data.forEach(val => {
                options.push({ label: val.formTypeName, value: val.kid });
            });
            this.setState(
                {
                    noPass: true,
                    options,
                    selectValue: options[0]?.value,
                },
                () => {
                    this.getWorkflowNode(this.state.selectValue);
                },
            );
        }
    };

    getWorkflowNode = async key => {
        const { userData } = this.props;
        const res = await axios({
            method: "get",
            url: "/workflow/findPreviewProcess",
            params: {
                processDefinitionKey: key,
                applyUserId: userData.userId,
                needPact: true,
                pactId: userData.pactId,
            },
        });
        if (res.success) {
            let { defCheckAll, isOneSelect, noPass, nodeList } = this.state;
            for (let i = 0; i < res.data.length; i++) {
                const ele = res.data[i];
                ele.personList = [];
                ele.person = "";
                if (defCheckAll) {
                    ele.checkAll = true; // 默认全选，打勾
                } else {
                    ele.checkAll = false; // 默认不选，不打勾
                }
                if (ele.assigneeList.length === 0) {
                    // 自选流程
                    if (
                        ele.nodeInfos.systemInfos.applicantOptionalAssignees &&
                        ele.nodeInfos.systemInfos.applicantOptionalAssigneesName
                    ) {
                        isOneSelect = true; //自选
                        ele.person += ele.nodeInfos.systemInfos.applicantOptionalAssigneesName;
                        //人员列表
                        let listuserName =
                            ele.nodeInfos.systemInfos.applicantOptionalAssigneesName.split(",");
                        let listuserId =
                            ele.nodeInfos.systemInfos.applicantOptionalAssignees.split(",");
                        if (defCheckAll) {
                            //全选人员
                            ele.selectUser = listuserName;
                        } else {
                            //不选择任何人
                            ele.selectUser = [];
                        }
                        if (listuserName.length === listuserId.length) {
                            for (let j = 0; j < listuserName.length; j++) {
                                ele.personList.push({
                                    userName: listuserName[j],
                                    userId: listuserId[j],
                                });
                            }
                        }
                    } else {
                        // 不选人不可点【确定】按钮
                        noPass = true; //有空值
                    }
                } else {
                    // 角色配置或其他配置
                    if (ele.nodeType === "CC") {
                        //抄送人默认全选，且不能取消
                        ele.disabled = true;
                        ele.selectUser = ele.assigneeList.map(e => {
                            return e.userName;
                        });
                    }
                    ele.personList = ele.assigneeList; // 审核人员列表
                    ele.selectUser = []; // 固定流程-发起人自己也可以全选
                    for (let j = 0; j < ele.assigneeList.length; j++) {
                        const ele2 = ele.assigneeList[j];
                        if (j < ele.assigneeList.length - 1) {
                            ele.person += ele2.userName + "，";
                        } else {
                            ele.person += ele2.userName;
                        }
                        // 固定流程-发起人自己也可以全选
                        ele.selectUser.push(ele2.userName);
                    }
                }
            }
            if (res.data.length > 0) {
                nodeList = [{ nodeId: "0", nodeName: "流程开始", person: "", startAndEnd: "yes" }];
            }
            nodeList = nodeList.concat(res.data);
            if (res.data.length > 0) {
                nodeList.push({
                    nodeId: "100",
                    nodeName: "流程结束",
                    person: "",
                    startAndEnd: "yes",
                });
            }
            this.setState({
                nodeList,
                defCheckAll,
                isOneSelect,
                noPass,
            });
        }
    };

    visibleCb = show => {
        this.setState({
            show: show || false,
        });
    };

    confirm = () => {
        const { page } = this.props;
        const { nodeList } = this.state;
        for (let i = 0; i < nodeList.length; i++) {
            const cur = nodeList[i];
            if (cur?.startAndEnd === "yes") {
                continue;
            }
            if (!cur.selectUser.length) {
                Toast.show({
                    icon: "fail",
                    content: `${cur.nodeName}节点至少要选择一人`,
                    duration: 1000,
                });
                return;
            }
        }
        if (page === "add" || page === "edit") {
            this.saveAndCommitHandle();
        } else {
            this.commitHandle();
        }
    };

    // 直接提交审核先保存
    saveAndCommitHandle = async () => {
        const { kid, formData, page, baseUrl } = this.props;
        const url = baseUrl + "_" + page;
        const res = await axios({
            method: "post",
            url,
            data: Object.assign({}, { kid }, formData),
        });
        if (res.success) {
            this.commitHandle();
        } else {
            Toast.show({
                icon: "fail",
                content: res.msg || "操作失败",
            });
        }
    };

    // 提交审核
    commitHandle = () => {
        const { kid } = this.props;
        const { selectValue, nodeList } = this.state;
        if (kid && selectValue) {
            let args = Object.assign(
                {},
                { businesskey: kid },
                { processDefinitionKey: selectValue },
                { variables: { nextUserIds: "" } },
                { applicantOptionalList: null },
            );
            //将下一步人员传到自定义变量中
            let userNodearr = []; //节点及选中人员
            let notnode = null;
            for (let i = 0; i < nodeList.length; i++) {
                const ele1 = nodeList[i];
                const lastIdx = nodeList.length - 1;
                const notIndex = i != 0 && i != lastIdx;
                const nodeType = ele1.nodeType;
                if (nodeType === "CC") {
                    continue;
                }
                ele1.selectUserObj = { nodeId: ele1.nodeId, assginees: "" };
                // 监理工作
                if (S_SYS_NAME === "gsm") {
                    if (nodeType === "ASSIGNEE_USERTASK") {
                        for (let i = 0; i < ele1.personList.length; i++) {
                            ele1.selectUserObj.assginees += ele1.personList[i].userId + ",";
                        }
                        if (ele1.selectUserObj && ele1.selectUserObj.assginees) {
                            ele1.selectUserObj.assginees = ele1.selectUserObj.assginees.substr(
                                0,
                                ele1.selectUserObj.assginees.length - 1,
                            );
                        }
                    } else if (nodeType === "APPLICANT_OPTIONAL_USERTASK") {
                        // 发起人自选
                        // 已选中
                        if (ele1.selectUser && ele1.selectUser.length > 0) {
                            for (let j = 0; j < ele1.selectUser.length; j++) {
                                for (let k = 0; k < ele1.personList.length; k++) {
                                    if (ele1.personList[k].userName === ele1.selectUser[j]) {
                                        ele1.selectUserObj.assginees +=
                                            ele1.personList[k].userId + ",";
                                    }
                                }
                            }
                            if (ele1.selectUserObj && ele1.selectUserObj.assginees) {
                                ele1.selectUserObj.assginees = ele1.selectUserObj.assginees.substr(
                                    0,
                                    ele1.selectUserObj.assginees.length - 1,
                                );
                            }
                        } else {
                            // 未选中 ：第一步骤，倒数第一步骤
                            if (notIndex) {
                                notnode = ele1;
                            }
                        }
                    }
                } else {
                    // 其他系统（除了：监理工作）
                    if (ele1.selectUser && ele1.selectUser.length > 0) {
                        for (let j = 0; j < ele1.selectUser.length; j++) {
                            for (let k = 0; k < ele1.personList.length; k++) {
                                if (ele1.personList[k].userName == ele1.selectUser[j]) {
                                    ele1.selectUserObj.assginees += ele1.personList[k].userId + ",";
                                }
                            }
                        }
                        if (ele1.selectUserObj && ele1.selectUserObj.assginees) {
                            ele1.selectUserObj.assginees = ele1.selectUserObj.assginees.substr(
                                0,
                                ele1.selectUserObj.assginees.length - 1,
                            );
                        }
                    } else {
                        // 未选中 ：第一步骤，倒数第一步骤
                        if (notIndex) {
                            notnode = ele1;
                        }
                    }
                }
                if (notIndex) {
                    userNodearr.push(ele1.selectUserObj);
                }
            }
            if (notnode) {
                Toast.show({
                    icon: "fail",
                    content: `${notnode.nodeName}节点至少要选择1人！`,
                });
                return false;
            }
            args.applicantOptionalList = userNodearr;
            //只提醒第一步的人员
            args.variables.nextUserIds =
                args &&
                args.applicantOptionalList &&
                args.applicantOptionalList.length > 0 &&
                args.applicantOptionalList[0].assginees;
            // 提交审核操作
            this.commitSignFun(args);
        }
    };

    commitSignFun = async args => {
        const { optionOne, commitCallBack } = this.props;
        const res = await axios({
            method: "post",
            url: this.state.commitUrl,
            data: {
                flowStartJsonStr: JSON.stringify(args),
                formType: (optionOne && optionOne.formType) || null,
                workflowModule: (optionOne && optionOne.workflowModule) || null,
            },
        });
        if (res.success) {
            Toast.show({
                icon: "success",
                content: "操作成功",
                duration: 1000,
            });
            this.visibleCb();
            commitCallBack && commitCallBack();
        } else {
            Toast.show({
                icon: "fail",
                content: res.msg || "操作失败",
                duration: 1000,
            });
        }
    };

    selectChange = val => {
        this.setState({
            selectValue: val,
        });
        this.getWorkflowNode(val);
    };

    handleCheckAllChange = (val, item) => {
        let { nodeList } = this.state;
        let noPass = false;
        const idx = nodeList.findIndex(node => node.nodeId === item.nodeId);
        if (!~idx) return;
        nodeList[idx] = {
            ...item,
            selectUser: val ? item.person.split(",") : [],
            checkAll: val,
        };
        const current = nodeList[idx];
        // 不选人不可点【确定】按钮
        if ((current.selectUser && current.selectUser.length === 0) || !val) {
            noPass = true;
        }
        this.setState({
            nodeList: [...nodeList],
            noPass,
        });
    };

    changeUser = (selectUser, item) => {
        let { nodeList } = this.state;
        let noPass = false;
        for (let i = 0; i < nodeList.length; i++) {
            const ele1 = nodeList[i];
            if (ele1.startAndEnd !== "yes") {
                // 不选人不可点【确定】按钮
                if (selectUser && selectUser.length === 0) {
                    noPass = true;
                }

                if (item.nodeId === ele1.nodeId) {
                    // 当前审核流的节点，去掉某个人选，就不全选
                    if (selectUser.length === ele1.personList.length) {
                        ele1.checkAll = true;
                    } else {
                        ele1.checkAll = false;
                    }
                    ele1.selectUser = selectUser;
                }
            }
        }
        this.setState({
            noPass,
            nodeList: [...nodeList],
        });
    };

    render() {
        const { show, noPass, nodeList, isOneSelect, options, selectValue } = this.state;
        const { commitCallBack } = this.props;

        const btns = [
            {
                label: "确定",
                key: "0",
                fn: () => this.confirm(),
                // disabled: noPass,
            },
            {
                label: "取消",
                key: "1",
                fn: () => this.visibleCb(),
            },
        ];
        return (
            <Popup
                visible={show}
                onMaskClick={this.visibleCb}
                onClose={this.visibleCb}
                bodyStyle={{ height: "78vh" }}
                showCloseButton
                className="workflow"
                closeOnMaskClick
            >
                <div className="workflow-container">
                    <h2>提交审核</h2>
                    <div className="select">
                        <h4>选择工作流</h4>
                        <Selector data={options} value={selectValue} onChange={this.selectChange} />
                    </div>
                    <WorkflowStep
                        isOneSelect={isOneSelect}
                        noPass={noPass}
                        nodeList={nodeList}
                        handleCheckAllChange={this.handleCheckAllChange}
                        changeUser={this.changeUser}
                    />
                </div>

                <Btns btns={btns} size="large" block />
            </Popup>
        );
    }
}

WorkflowCommit.displayName = "WorkflowCommit";
WorkflowCommit.propTypes = {
    commitCallBack: PropTypes.func,
    baseUrl: PropTypes.string,
    formData: PropTypes.object,
    optionOne: PropTypes.object,
    workflowModule: PropTypes.string,
    userData: PropTypes.object,
    page: PropTypes.oneOf(["add", "edit", "view", ""]),
    kid: PropTypes.string,
};

export default WorkflowCommit;
